<template>
  <view class="select-location">
    <!-- 顶部搜索框 -->
    <view id="top">
      <view id="search" class="input-box flex-row align-center">
        <text class="tbb-search text-30 color-t1 flex-row flex-center margin-right-10" />
        <input disabled type="text" class="text-30 flex-item" style="flex: 0.9" @click="goSearch" placeholder="关键词搜索" placeholder-class="text-t3" />
		<cover-image class="current-icon" src="@/static/point.png"
		@click="backCurrentLocation"
		 />
      </view>
      <map
        id="map"
        class="map relative"
        :latitude="latitude"
        :longitude="longitude"
        @regionchange="changeEvent"
		show-location
      >
        <!-- 定位标志 -->
        <cover-image class="location-icon" src="https://tbb-file.oss-cn-shenzhen.aliyuncs.com/tbb_admin_app/icon/location.png" />
        <!-- tip -->
        <cover-view class="tip text-24 color-t3 padding-lr-20 padding-tb-10">您可以拖动地图，标记当前精准位置</cover-view>
      </map>
    </view>

    <scroll-view :style="{height}" scroll-y>
      <view class="padding-bottom-button">
        <view v-for="item in list" :key="item.id" class="padding-lr-30">
          <l-radio
            :checked="active.id === item.id"
            :item="item"
            has-slot
            space="30rpx"
            padding="15rpx 0"
            @click="selectedAddress(item)"
          >
            <view class="flex-column">
              <text class="text-30 color-t1" :class="{'color-primary':active.id === item.id}">{{ item.name }}</text>
              <text class="text-24 color-t3" :class="{'color-primary':active.id === item.id}">{{ item.address }}</text>
            </view>
          </l-radio>
        </view>
      </view>
      <safe-area-bottom />
    </scroll-view>

    <l-bottom-button background="#ffffff" text="确认位置" @click="handleConfirm" />
  </view>
</template>

<script>
import debounce from 'lodash/debounce'
import { mapGetters, mapMutations } from 'vuex'
import { loading } from '@/common/util'
import { reverseGeocoder } from '../index'
export default {
  name: 'TbbMapSelect',
  data() {
    return {
      height: '',
      keyword: '',
      active: '',
      location: '',
      latitude: '',
      longitude: '',
      list: [],
      mapContext: null,
      changeEvent: debounce(this.handleRegionChange, 300),
      path: '',
      touch: true,
      loading: null
    }
  },
  computed: {
    ...mapGetters({
	  selectFromTo: 'selectFromTo',
      selectedLocation: 'selectedLocation',
      selectedSearch: 'selectedSearch'
    })
  },
  onShow() {
    if (this.selectedSearch) {
      this.location = this.selectedSearch.location
      const locations = this.selectedSearch.location.split(',')
      this.mapContext.moveToLocation({
        longitude: locations[0],
        latitude: locations[1]
      })
      this.getLocationInfo(this.selectedSearch.location)
    }
  },
  onLoad(params) {
    this.path = params.path
	this.mapContext = uni.createMapContext('map', this)
    this.getCurrentLocation()
  },
  mounted() {
    this.getHeight()
  },
  beforeDestroy() {
    this.setSelectedSearch(null)
  },
  methods: {
    // 获取当前坐标 或者 已经定位过的坐标
    getCurrentLocation() {
		const {longitude, latitude} = (this.selectFromTo || {})[this.path] || {}
		console.log(longitude, latitude, this.selectFromTo)
		if (longitude && latitude) {
			this.longitude = longitude
			this.latitude = latitude
		}
		else {
			this.backCurrentLocation()
		}
		
    },
	backCurrentLocation() {
		uni.authorize({
			scope: 'scope.userLocation',
			success: () => {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						this.longitude = res.longitude
						this.latitude = res.latitude
						if (this.mapContext) {
							this.mapContext.moveToLocation({
							  longitude: res.longitude,
							  latitude: res.latitude
							})
							this.mapContext.getCenterLocation({
							  success: res => {
							    const { longitude, latitude } = res
							    this.getLocationInfo(longitude + ',' + latitude)
							  }
							})
						}
						
					}
				})
			}
		})
	},
    // 获取列表高度
    getHeight() {
      const wHeight = this.sysInfo().windowHeight
      this.getElementInfo('#top', res => {
        this.height = wHeight - res.height + 'px'
      })
    },
    // 获取附近地址信息
    getLocationInfo(location) {
      reverseGeocoder(location).then(res => {
        // this.loading.hide()
        const pois = res.pois
        if (this.selectedLocation) {
          const index = pois.findIndex(item => item.id === this.selectedLocation.id)
          if (index > -1) pois.splice(index, 1)
          pois.unshift(this.selectedLocation)
        } else if (this.selectedSearch) {
          const index = pois.findIndex(item => item.id === this.selectedSearch.id)
          if (index > -1) pois.splice(index, 1)
          pois.unshift(this.selectedSearch)
        }
        if (pois.length) {
          this.active = pois[0]
        }
        this.list = pois
      })
    },
    // 点击列表选择地址
    selectedAddress(item) {
      this.touch = false
      this.active = item
      const locations = item.location.split(',')
	  let [longitude, latitude] = locations
	  if (longitude && latitude) {
		  this.mapContext.moveToLocation({
		    longitude: Number(longitude),
		    latitude: Number(latitude)
		  })
		  this.longitude = longitude
		  this.latitude = latitude
		  console.log(this.longitude, this.latitude)
	  }
      
    },
    // 移动地图获取坐标
    handleRegionChange(e) {
      if (!this.touch) {
        this.touch = true
        return
      }
      if ((e.type === 'end' && e.causedBy === 'drag') || e.type === 'regionchange') {
        this.setSelectedLocation(null)
        this.setSelectedSearch(null)
        this.mapContext.getCenterLocation({
          success: res => {
            const { longitude, latitude } = res
            this.getLocationInfo(longitude + ',' + latitude)
          }
        })
      }
    },
    // 搜索
    goSearch() {
      this.jump(`/order/map-select/search?location=${this.location}`)
    },
    // 确认选择
    handleConfirm() {
      this.active.path = this.path
      this.setSelectMapResult(this.active)
	  const locations = this.active.location.split(',')
	  let [longitude, latitude] = locations
	  if (longitude && latitude) {
		this.setSelectedFromTo({[this.active.path]: {longitude, latitude}})
	  }
	  
      this.jump()
    },
    ...mapMutations({
	  setSelectedFromTo: 'order/setSelectedFromTo',
      setSelectedLocation: 'order/setSelectedLocation',
      setSelectedSearch: 'order/setSelectedSearch',
      setSelectMapResult: 'order/setSelectMapResult'
    })
  }
}
</script>
<style lang="scss" scoped>
@include setPadding(tb,15);

.top{
  @include position(sticky,$top:0);
}
.map {
  width: 750rpx;
  height: 600rpx;
}
.location-icon {
  width: 64rpx;
  height: 64rpx;
  @include position(absolute, $top: 50%, $left: 50%);
  transform: translate(-50%, -50%);
}

.current-icon {
  width: 32rpx;
  height: auto;
  @include position(absolute, $top: 50%, $right: 5%);
  transform: translate(-50%, -50%);
}
.tip {
  @include position(absolute, $bottom: 30rpx, $left: 50%);
  box-shadow: 0 2rpx 10rpx 2rpx rgba(153, 153, 153, 0.34);
  background-color: $color-background;
  border-radius: 8rpx;
  transform: translateX(-50%);
}
</style>
